import 'dart:async';

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import "package:common_utils/common_utils.dart";

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

void main() async {
  flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '背景音',
      theme: new ThemeData(
        primaryColor: Colors.grey,
      ),
      home: _MyHomePage(),
    );
  }
}

class _MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<_MyHomePage> {
  int _selectedIndex = 0;
  int _heartbeat_time = 300; //心跳时间,用来保活，5分钟调用一次
  int _setTimeInt = -1;
  String _setTimeValue = '定时';
  Timer _timer;
  Timer _settimer;
  var progressValueList = [
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0
  ];
  AudioCache audioCache = new AudioCache();
  var AudioPlayerMap = {};
  var makePlayerState = 0; //播放操作状态，防抖动导致短时间内的双击造成播放器重复创建问题。
  int _isPlay = 0; //是否正在播放,用来控制通知栏播放状态

  @override
  initState() {
    super.initState();
    // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
    var initializationSettingsAndroid =
        AndroidInitializationSettings('app_icon');
    var initializationSettingsIOS = IOSInitializationSettings();
    var initializationSettings = InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  @override
  Widget build(BuildContext context) {
    Widget titleSection = Container(
      padding: const EdgeInsets.all(28),
      child: Row(
        children: [
          Expanded(
            /*1*/
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                /*2*/
                Container(
                  child: Text(
                    '自然背景音',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Text(
                  '滑动按钮调配背景音',
                  style: TextStyle(
                    color: Colors.grey[500],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );

    Widget sliderSection = Container(
      padding: const EdgeInsets.all(5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          /*2*/
          Container(
            padding: const EdgeInsets.all(3),
            child: Row(
              children: [
                _buildNoiseExpanded(const Color(0xFF7C846B), '雨打芭蕉', 'rain.ogg',
                    0xe600, progressValueList[0], 0),
                _buildNoiseExpanded(const Color(0xFF9C7264), '春雷阵阵',
                    'thunders.ogg', 0xe686, progressValueList[1], 1),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(3),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildNoiseExpanded(const Color(0xFF707253), '温馨小屋',
                    'rain_on_window.ogg', 0xe667, progressValueList[2], 2),
                _buildNoiseExpanded(const Color(0xFF516875), '车流涌动', 'car.ogg',
                    0xe66c, progressValueList[3], 3),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(3),
            child: Row(
              children: [
                _buildNoiseExpanded(const Color(0xff5E6941), '清风徐徐', 'wind.ogg',
                    0xe6a4, progressValueList[4], 4),
                _buildNoiseExpanded(const Color(0xFF534943), '林中漫步',
                    'forest.ogg', 0xec3c, progressValueList[5], 5),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(3),
            child: Row(
              children: [
                _buildNoiseExpanded(const Color(0xFFA69A6C), '小河淌淌',
                    'creek.ogg', 0xe632, progressValueList[6], 6),
                _buildNoiseExpanded(const Color(0xFFA17055), '雨意漫布',
                    'leaves.ogg', 0xe9b3, progressValueList[7], 7),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(3),
            child: Row(
              children: [
                _buildNoiseExpanded(const Color(0xFF808A74), '红泥小炉', 'fire.ogg',
                    0xe6a0, progressValueList[8], 8),
                _buildNoiseExpanded(const Color(0xFFC9AE9B), '浪花朵朵',
                    'ocean.ogg', 0xe628, progressValueList[9], 9),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(3),
            child: Row(
              children: [
                _buildNoiseExpanded(const Color(0xFF744B38), '火车远行',
                    'train.ogg', 0xe614, progressValueList[10], 10),
                _buildNoiseExpanded(const Color(0xFFC79A77), '夜深人静',
                    'night.ogg', 0xe602, progressValueList[11], 11),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(3),
            child: Row(
              children: [
                _buildNoiseExpanded(const Color(0xFF594F6E), '咖啡屋内', 'cafe.ogg',
                    0xe6fa, progressValueList[12], 12),
                _buildNoiseExpanded(const Color(0xFF617C8F), '纯白噪音',
                    'whitenoise.ogg', 0xe637, progressValueList[13], 13),
              ],
            ),
          ),
        ],
      ),
    );
    return MaterialApp(
      title: '自然背景音',
      theme: new ThemeData(
        primaryColor: Colors.grey,
      ),
      home: Scaffold(
        body: ListView(
          children: [
            Image.asset(
              'images/listen.jpg',
              width: 600,
              height: 130,
              fit: BoxFit.cover,
            ),
            titleSection,
            sliderSection
          ],
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
                icon: Icon(Icons.play_arrow), title: Text('播放')),
            BottomNavigationBarItem(icon: Icon(Icons.stop), title: Text('暂停')),
            BottomNavigationBarItem(
                icon: Icon(Icons.access_time), title: Text(_setTimeValue)),
          ],
          type: BottomNavigationBarType.fixed,
          currentIndex: _selectedIndex,
          fixedColor: Colors.deepPurple,
          onTap: _onItemTapped,
        ),
      ),
    );
  }

  Row _buildButtonRow(Color color, IconData icon, String label) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          child: Text(
            label,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ),
        Icon(icon, color: color, size: 12),
      ],
    );
  }

  Container _buildNoiseContainer(
      Color color, String name, progressValue, int sortNumber) {
    return Container(
        width: 140,
        height: 30,
        color: Colors.grey[100],
        padding: const EdgeInsets.all(3),
        margin: const EdgeInsets.all(3),
        child: new Slider(
          value: progressValue, //实际进度的位置,
          label: '$progressValue',
          max: 100.0,
          min: 0.0,
          divisions: 1000,
          activeColor: color,
          onChanged: (double) {
            setState(() {
              progressValueList[sortNumber] = double.roundToDouble();
              print(progressValueList[sortNumber]);
              _playLocal('$name', progressValueList[sortNumber]);
            });
          },
        ));
  }

  Expanded _buildNoiseExpanded(Color color, String label, String name, int icon,
      double progressValue, int sortNumber) {
    return Expanded(
      /*1*/
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          /*2*/
          _buildButtonRow(color, IconData(icon, fontFamily: 'iconfont'), label),
          _buildNoiseContainer(color, name, progressValue, sortNumber),
        ],
      ),
    );
  }

  Future<void> _showNotification() async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        playSound: false,
        enableVibration: false,
        autoCancel: false,
        importance: Importance.Max,
        priority: Priority.High);
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(0, '自然背景音正在运行',
        '不要清理此通知信息！保证自然背景音进程不会中断！', platformChannelSpecifics,
        payload: 'item x');
  }

  //收藏
  void _getFavorites() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          return new Scaffold(
            appBar: new AppBar(
              title: new Text('Saved Suggestions'),
            ),
            body: new Text('HELLO'),
          );
        },
      ),
    );
  }

  void _onItemTapped(int index) {
    setState(() {
      if (index == 1) {
        this.AudioPlayerMap.forEach((k, v) {
          if (v.state == AudioPlayerState.PLAYING) {
            v.stop();
          }
        });
      } else if (index == 0) {
        _resume();
      } else if (index == 2) {
        _getTime();
      }
      _selectedIndex = index;
    });
  }

  void _playLocal(localPath, volume) async {
    volume = volume / 100;
    if (this.AudioPlayerMap.containsKey(localPath) != true &&
        this.makePlayerState == 0) {
      this.makePlayerState = 1;
      _resume();
      print("---------------------------------");
      print(this.AudioPlayerMap);
      print(this.AudioPlayerMap.isEmpty);
      if (this.AudioPlayerMap.isEmpty) {
        //第一次触发播放开启定时停止重播得定时任务
        print("11111111");
        _countdown();
      }
      this.AudioPlayerMap[localPath] =
          await audioCache.loop(localPath, volume: volume);
      this.makePlayerState = 0;
    } else {
      _resume();
      this.AudioPlayerMap[localPath].setVolume(volume);
    }
    _checkPlay();
  }

  void _resume() async {
    if (this.AudioPlayerMap.isNotEmpty) {
      this.AudioPlayerMap.forEach((k, v) {
        if (v.state != AudioPlayerState.PLAYING) {
          v.resume();
        }
      });
    }
  }

  void _stop() async {
    if (this.AudioPlayerMap.isNotEmpty) {
      this.AudioPlayerMap.forEach((k, v) {
        if (v.state == AudioPlayerState.PLAYING) {
          v.stop();
        }
      });
    }
  }

  void _checkPlay() async {
    if (this.AudioPlayerMap.isNotEmpty) {
      this.AudioPlayerMap.forEach((k, v) {
        _showNotification();
      });
    }
  }

  //这里定时有两个功能1个是保活，一个是界面里得选择倒计时得定时
  //保活定时 start
  void _countdown() async {
    print("222222222");
    _timer =
        new Timer.periodic(new Duration(seconds: _heartbeat_time), (timer) {
      print("33333333");
      // 只在倒计时结束时回调
      _replay();
    });
  }

  //定时停止，然后再播放用,保活
  void _replay() async {
    if (this.AudioPlayerMap.isNotEmpty) {
      this.AudioPlayerMap.forEach((k, v) {
        v.stop();
        v.resume();
      });
      print('+++++++++++++++++++replay++++++++++++++++++++');
    }
  }
  //保活定时 end

  //界面里得倒计时 start
  //定时按钮触发得定时功能
  //定时
  void _getTime() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          return new Scaffold(
            appBar: new AppBar(
              title: new Text('定时'),
            ),
            body: new ListView(
              children: <Widget>[

                Card(
                  child: ListTile(
                    leading: Icon(Icons.looks_one),
                    title: Text('半小时'),
                    onTap: () {
                      setState(() {
                        _setTime(30*60);
                      });
                    },
                  ),
                ),
                Card(
                  child: ListTile(
                    leading: Icon(Icons.looks_two),
                    title: Text('1小时'),
                    onTap: () {
                      setState(() {
                        _setTime(3600);
                      });
                    },
                  ),
                ),
                Card(
                  child: ListTile(
                    leading: Icon(Icons.looks_3),
                    title: Text('2小时'),
                    onTap: () {
                      setState(() {
                        _setTime(2 * 3600);
                      });
                    },
                  ),
                ),
                Card(
                  child: ListTile(
                    leading: Icon(Icons.looks_4),
                    title: Text('4小时'),
                    onTap: () {
                      setState(() {
                        _setTime(4 * 3600);
                      });
                    },
                  ),
                ),
                Card(
                  child: ListTile(
                    leading: Icon(Icons.looks_5),
                    title: Text('8小时'),
                    onTap: () {
                      setState(() {
                        _setTime(8 * 3600);
                      });
                    },
                  ),
                )
              ],
            ),
          );
        },
      ),
    );
  }

  void _setTime(int time) {
    //time 秒
    setState(() {
      _cancelSetTimer();
      _setTimes(time);
      _resume();
      Navigator.of(context).pop();
    });
  }


  void _changeTime(int time) {
    setState(() {
      print(time);
      var date = new DateTime.fromMillisecondsSinceEpoch(
          time * 1000 - 3600 * 1000 * 8); //单位要转成微妙
      print(date);
      String setTime = DateUtil.getDateStrByDateTime(date,
          format: DateFormat.HOUR_MINUTE_SECOND); //2018年09月16日 23时16分15秒
      print(setTime);
      _setTimeValue = setTime;
    });
  }

  //定时播放功能
  void _setTimes(int time) async {
    _setTimeInt = time;
    _settimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
      if (_setTimeInt == 0) {
        _cancelSetTimer();
        _stop();
        return;
      }
      _setTimeInt--;
      _changeTime(_setTimeInt);
    });
  }

  /// 取消倒计时的计时器。
  void _cancelSetTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _settimer?.cancel();
  }
//界面里得倒计时 end

}
